<template>
    <div style="background-color: white; padding: 10px">
        <a-input-search v-model="input" allowClear
                        enter-button
                        placeholder="请输入用户名搜索"
                        style="width: 250px"
                        @search="getManagers"/>


        <a-modal :visible="visible" size="small" title="编辑账号" @cancel="visible=false"
                 @ok="updateUser">
            <a-form :form="form">
                <a-form-item label="用户id" style="display: none">
                    <a-input
                        v-decorator="['id', { rules: [{ required: false, message: '请输入用户名!' }] }]"
                    />
                </a-form-item>
                <a-form-item label="用户名">
                    <a-input
                        v-decorator="['username', { rules: [{ required: true, message: '请输入用户名!' }] }]"
                    />
                </a-form-item>
                <a-form-item label="账号">
                    <a-input
                        v-decorator="['account', { rules: [{ required: true, message: '请输入账号!' }] }]"
                    />
                </a-form-item>
                <a-form-item label="密码">
                    <a-input-password v-decorator="['password',{ rules: [{ required: true, message: '请输入密码!' }] },]"
                                      placeholder="请输入原密码"/>
                </a-form-item>

                <a-form-item label="新密码">
                    <a-input-password
                        v-decorator="['pawssword_two',{ rules: [{ required: false, message: '请输入新密码!' }] },]"
                        placeholder="可以输入您的新密码"/>
                </a-form-item>
            </a-form>
        </a-modal>
        <a-table :columns="columns" :data-source="data"
                 :pagination="false"
                 :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                 rowKey="id">

            <span slot="addtime" slot-scope="addtime">
                {{
                    moment(addtime * 1000).format("YYYY-MM-DD HH:mm:ss")
                }}
            </span>
            <div slot="mark" slot-scope="item">
                <a-switch :checked="item.mark!==0" checked-children="开启" un-checked-children="关闭"
                          @change="updateMark(item)"></a-switch>
            </div>

            <div slot="action" slot-scope="item">
                <a-button size="small" type="primary" @click="editUser(item)">编辑</a-button>
                <a-button size="small" type="danger" @click="deleteUser(item.id)">删除</a-button>
            </div>
        </a-table>

        <a-row>
            <a-col span="12">
                <div style="margin-left: 16px">
                    <a-button :disabled="!hasSelected" type="primary" @click="batchDelete">
                        批量删除
                    </a-button>

                    <span style="margin-left: 8px">
                        <template v-if="hasSelected">
                          {{ `共 ${selectedRowKeys.length} 条` }}
                        </template>
                    </span>
                </div>

            </a-col>
            <a-col span="12">
                <a-pagination v-model="page" :default-current="2"
                              :pageSize="pageSize"
                              :pageSizeOptions="['5','10', '20', '30', '40']"
                              :showSizeChanger="true"
                              :showTotal="total => `共 ${total} 条`"
                              :total="total"
                              show-quick-jumper
                              @change="getManagers" @showSizeChange="(page,size)=> {pageSize = size;getManagers()}"/>
            </a-col>
        </a-row>

    </div>
</template>

<script>
import {METHOD, request, RESPONSE} from "@/utils/request";
import moment from "moment";

const columns = [
    {
        title: '编号',
        key: 'id',
        dataIndex: 'id'
    },
    {
        title: '用户名',
        key: 'username',
        dataIndex: 'username'
    },
    {
        title: '账号',
        key: 'account',
        dataIndex: 'account'
    },
    {
        title: '添加时间',
        key: 'addtime',
        dataIndex: 'addtime',
        scopedSlots: {customRender: 'addtime'},
    },
    {
        title: '是否显示',
        key: 'mark',
        scopedSlots: {customRender: 'mark'},
    },
    {
        title: '操作',
        key: 'action',
        scopedSlots: {customRender: 'action'},
    },
]

export default {
    name: 'TaskCard',
    data() {
        return {
            input: null,
            form: this.$form.createForm(this, {name: 'coordinated'}),
            visible: false,
            moment,
            data: null,
            columns,
            selectedRowKeys: [],
            page: 1,
            pageSize: 5
        }
    },
    computed: {
        hasSelected() {
            return this.selectedRowKeys.length > 0;
        },
    },
    mounted() {
        this.userID = JSON.parse(localStorage.getItem(process.env.VUE_APP_USER_KEY)).id;

        this.getManagers()
    },
    methods: {
        updateMark(item) {
            request("/user/updateMarkByid?id=" + item.id + "&mark=" + (item.mark === 0 ? 1 : 0), METHOD.PUT).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.getManagers();
                    this.$message.success(res.data.data);
                } else {
                    this.$message.error(res.data.msg);
                }
            })
        },
        updateUser() {
            this.form.validateFields((err, user) => {
                if (!err) {
                    request("/user/updateUserByid", METHOD.PUT, user).then(res => {
                        if (res.data.code === RESPONSE.SUCCESS_CODE) {
                            this.getManagers();
                            this.form.resetFields();
                            this.visible = false;
                            this.$message.success(res.data.msg);
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    })
                }
            });
        },
        editUser(item) {
            item.password = null;
            this.visible = true;
            // 在下次 DOM 更新循环结束之后执行延迟回调,解决设置form内的值失败的问题
            this.$nextTick(() => {
                this.form.setFieldsValue(item)
            })
        },
        deleteUser(id) {

            let that = this;
            this.$confirm({
                title: "删除后将不能恢复，确认删除吗？",
                onOk() {
                    let ids = [];
                    if (typeof id === typeof 1) {
                        // 传入的是一个id,添加进入数组
                        ids.push(id.toString());
                    } else {
                        for (let item of id) {
                            ids.push(item.toString());
                        }
                    }
                    request("/user/deleteUserByid", METHOD.DELETE, null, {
                        data: {
                            ids: ids
                        }
                    }).then(res => {
                        if (res.data.code === RESPONSE.SUCCESS_CODE) {
                            that.getManagers(null);
                            that.$message.success(res.data.data);
                        } else {
                            that.$message.error(res.data.msg);
                        }
                    })
                }
            })
        },
        getManagers() {
            request("/user/getUserlist", METHOD.GET, {
                id: this.userID,
                page: this.page,
                pageSize: this.pageSize,
                input: this.input
            }).then(res => {
                if (res.data.code === RESPONSE.SUCCESS_CODE) {
                    this.data = res.data.data.records;
                    this.total = res.data.data.total;
                    // 清空左侧选中状态
                    this.selectedRowKeys = []
                } else {
                    this.$message.error(this.data.msg);
                }
            })
        },
        onSelectChange(selectedRowKeys) {
            console.log('selectedRowKeys changed: ', selectedRowKeys);
            this.selectedRowKeys = selectedRowKeys;
        },
        batchDelete() {
            this.deleteUser(this.selectedRowKeys)
        }
    }
}
</script>

<style lang="less" scoped>

</style>
